<template>
  <div ref="containerRef">
    <!-- 数据为以下内容, 模仿从excel 中粘贴到的数据
      姓名 生日 地址
      李白 20220-01-01 111
      王维 20220-01-10 222
      杜甫 20220-10-01 333 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="date" label="Date" width="180" />
      <el-table-column prop="name" label="Name" width="180" />
      <el-table-column prop="address" label="Address" />
    </el-table>
  </div>

  <ElDialog title="粘贴事件" v-model="dialogPaste">
    <div>粘贴的数据识别为:</div>
    <div style="display: inline-flex; align-items: center;">
      <span>是否添加?</span>
      <el-button link type="primary" @click="yesClick">是</el-button>
      <el-button link @click="noClick">否</el-button>
    </div>
    <el-table :data="pasteData" style="width: 100%">
      <el-table-column prop="date" label="Date" width="180" />
      <el-table-column prop="name" label="Name" width="180" />
      <el-table-column prop="address" label="Address" />
    </el-table>
  </ElDialog>
</template>

<script lang="ts" setup>
import { ElDialog } from 'element-plus';
import { onMounted, ref } from 'vue';

type ITableData = {
  date: string,
  name: string,
  address: string
}

const tableData = ref([
  {
    date: '2016-05-03',
    name: '张三',
    address: '北京市',
  },
  {
    date: '2016-05-02',
    name: '李四',
    address: '天津市',
  },
  {
    date: '2016-05-04',
    name: '王五',
    address: '深圳市',
  },
  {
    date: '2016-05-01',
    name: '赵六',
    address: '广州市',
  },
])

const dialogPaste = ref(false);
const containerRef = ref<HTMLDivElement>()
const pasteData = ref<ITableData[]>([]);
onMounted(() => {
  containerRef.value?.addEventListener("paste", (event) => {
    event.preventDefault();

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    let paste = (event.clipboardData || window.clipboardData).getData("text");
    paste = paste.toUpperCase();
    pasteData.value = parseTableToJSON(paste);
    dialogPaste.value = true;
  })
})

const yesClick = () => {
  tableData.value.push(...pasteData.value)
  dialogPaste.value = false;
  pasteData.value = [];
}

const noClick = () => {
  dialogPaste.value = false;
  pasteData.value = [];
}

function parseTableToJSON(tableText: string) {
  // 按行分割，并过滤空行
  const lines = tableText.trim().split('\n').filter(line => line.trim() !== '');

  // 跳过表头（第一行）
  const dataLines = lines.slice(1);

  // 映射每行为一个对象
  const result = dataLines.map(line => {
    const [name, date, address] = line.trim().split(/\s+/); // 使用一个或多个空白字符分割
    console.log(`output->line.split(/\s+/)`, line.split(/\s+/))
    return {
      name: name,
      date: date,
      address: address
    };
  });

  return result;
}

</script>
